﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Web;

namespace formworks
{
    /// <summary>
    /// dotNet版Servlet 实现IHttpHandler接口
    /// web.config下 指定例如
    /// <add verb="*" path="*.aspx" type="formworks.Servlet"/>
    /// </summary>
    public class ServiceMapping : IHttpHandler
    {
        public DataSet ds;
        public ServiceMapping()
        {
            ds = new DataSet();
            
            string path = //System.Web.HttpContext.Current.Server.MapPath("./Config.xml");
            HttpContext.Current.Server.MapPath(
                HttpContext.Current.Request.ApplicationPath + "/ServiceMapping.xml");
            ds.ReadXml(path);
        }

        #region IHttpHandler 成员

        public void ProcessRequest(System.Web.HttpContext ctx)
        {
            try
            {
                string name = ctx.Request.Url.AbsolutePath;
                name = name.Substring(0, name.IndexOf('.'));
                //
                DataRow[] dc = ds.Tables[0].Select("url ='" + name + "'");
                if (dc.Length > 0)
                {
                    string className = dc[0]["Class"].ToString();
                    //加载程序集空间
                    //Assembly ass = Assembly.Load(
                    //    className.ToString().Substring(0, className.LastIndexOf('.')));
                    Assembly ass = Assembly.Load(
                        className.ToString().Substring(0, className.IndexOf('.')) );
                    //构建类型
                    Type ht = ass.GetType(dc[0]["Class"].ToString());
                    //发射创建对象
                    object obj = Activator.CreateInstance(ht);
                    //获取方法
                    MethodInfo mi = ht.GetMethod(dc[0]["function"].ToString());
                    //设置委托的方法的request参数
                    
                    object objRtn = mi.Invoke(obj, new object[] { ctx.Request });
                 
                    //if(mi.IsGenericMethod)
                    //  mi.MakeGenericMethod(typeof(ht)).Invoke(obj, new object[] { ctx.Request });

                    ctx.Response.Charset = "UTF-8";
                    //返回委托方法的结果到用户
                    ctx.Response.Write(objRtn as string);
                    ctx.Response.Flush();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
        #endregion
    }
}
